import React, { Component } from 'react';
import { Modal, Button } from 'antd';
import isEqual from 'lodash/isEqual';
import { compare } from '@/utils/utils';
import btnIcon from '../../assets/select-btn.png';

export default class SelectSystem extends Component {
  constructor(props) {
    super(props);
    this.state = {
      systemList: props.systemList || [],
      sysId: '',
    };
  }

  static getDerivedStateFromProps(nextProps, preState) {
    if (isEqual(nextProps.systemList, preState.systemList)) {
      return null;
    }
    return {
      systemList: nextProps.systemList,
    };
  }

  // 隐藏模态框
  hideModelHandler = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'login/logout',
    });
  };

  // 选择一系统
  selectSystem = sysId => {
    const { systemList } = this.props;
    systemList.map(item => {
      if (item.sysId === sysId) {
        item.isSelected = true;
        this.setState({ sysId: item.sysId });
      } else {
        item.isSelected = false;
      }
    });
    this.setState({ systemList });
  };

  // 提交数据
  submitData = async () => {
    const { dispatch } = this.props;
    const { sysId, systemList } = this.state;
    await dispatch({
      type: 'login/fetchAuthorityList',
      payload: { sysId },
    });
    await dispatch({
      type: 'login/setLoginInfo',
      payload: { systemList },
    });
    await dispatch({
      type: 'login/setCurrentSystemBySysID',
      payload: { sysId },
    });
  };

  render() {
    const { systemList, visableModal } = this.props;
    return (
      <div>
        <Modal
          title="选择登录系统"
          visible={visableModal}
          maskClosable={false}
          okText="继续"
          cancelText="取消"
          onOk={this.submitData}
          onCancel={this.hideModelHandler}
          okButtonProps={{ disabled: !systemList.some(item => item.isSelected) }}
          destroyOnClose
        >
          {systemList.sort(compare('sysCode')).map(item => (  
            <div key={item.sysId} style={{ textAlign: 'center' }}>
              <Button
                style={{ marginBottom: 10, height: 40, width: 300 }}
                onClick={() => this.selectSystem(item.sysId)}
              >
                {item.sysName}
                {item.isSelected ? (
                  <img
                    alt="图片显示错误"
                    src={btnIcon}
                    style={{ position: 'absolute', top: 12, right: 0, width: 26, height: 26 }}
                  />
                ) : null}
              </Button>
            </div>
          ))}
        </Modal>
      </div>
    );
  }
}
